package cn.yunyichina.provider.base.dao.sync.impl;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ResourceBundle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fy.util.AppException;
import com.fy.util.db.DaoConfig;
import com.fy.util.db.JdbcDao;


public class ImportSourceDao extends JdbcDao implements AutoCloseable {
	
	private static final Logger logger = LoggerFactory.getLogger(ImportSourceDao.class);

	static ThreadLocal<Connection> tlCon = new ThreadLocal<Connection>();

	public ImportSourceDao() {
		this.setDatabaseType(DaoConfig.DATABASE_TYPE_MYSQL);
		this.setUserControlConnection(true);
	}
	
	static ResourceBundle rb;
	static {
		rb = ResourceBundle.getBundle("conf.jdbc");
	}
	
	/**
	 * 判断是否是正式环境，根据jdbc.properties里的url里的IP地址判断
	 * @return
	 */
	public static boolean isRelease() {
		//是否是正式环境
		boolean releaseFlag = false;
		try {
			if (rb.getString("jdbc.url").indexOf("10.46.126.158")>0) {
				//正式环境
				releaseFlag = true;
			}
		} catch (Exception e) {
			logger.error("读取jdbc.properties错误，无法获取是否是正式环境");
			e.printStackTrace();
		}
		return releaseFlag;
	}
	
	/**
	 * 判断同步是否可以运行
	 * @return
	 */
	public static boolean isCanRun() {
		//是否是正式环境
		boolean canRunFlag = false;
		try {
			if (rb.containsKey("sync.run") && rb.getString("sync.run").equals("true")) {
				//正式环境
				canRunFlag = true;
			}
		} catch (Exception e) {
			logger.error("读取jdbc.properties错误，无法获取是否是正式环境");
			e.printStackTrace();
		}
		return canRunFlag;
	}
	@Override
	public Connection getConnection() {
		Connection innerCon = tlCon.get();
		try {
			
			if (innerCon != null &&( ! innerCon.isClosed())) {
				return innerCon;
			}
			
			String strDriver = "com.mysql.jdbc.Driver";
			Class.forName(strDriver);
			if (isRelease()) {
				//正式
				String url = "jdbc:mysql://112.74.86.135:3306/test?characterEncoding=UTF8";
				innerCon = DriverManager.getConnection(url, "yunyi", "yunyi2016");
			}
			else {
				//测试
				String url = "jdbc:mysql://120.25.126.28:3306/test?characterEncoding=UTF8";
				innerCon = DriverManager.getConnection(url, "yunyi", "yunyi2016"); 
			}
			tlCon.set(innerCon); 
			

		} catch (Exception se) {
			throw new AppException("数据库连接错误", se);
		}

		return innerCon;

	
	}
	
	@Override
	public void releaseCon() {

		if (!this.isUserControlConnection()) {
			return;
		}

		int iCloseConnection = this.getCountCloseConnection();
		if (iCloseConnection > 0) {
			return;
		}
		Connection innerCon = this.getConnection();

		if (innerCon != null) {
			try {
				
				innerCon.close();
				tlCon.remove();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		innerCon = null;

	}
	@Override
	public void close() throws Exception {
		releaseCon();
		
	}
}
